/**
 * @description 用户关系的数据库层
 * @author 印明帝
 */
const { User, UserRelation } = require('../db/model/index')
const { formatUser } = require('./_format')
const Sequelize = require('sequelize')


/**
 * 添加关注关系
 * @method addFollower
 * @param {number} userId 用户 id 
 * @param {number} followerId 关注的用户 id
 * @returns {Promise}
 */
async function addFollower(userId,followerId) {
  let result = await UserRelation.create({
    userId,
    followerId
  })
  return result.dataValues
}

/**
 * 取消关注关系
 * @method deleteFollower
 * @param {number} userId 用户 id
 * @param {number} followerId 关注的用户 id
 * @returns {Promise}
 */
async function deleteFollower(userId,followerId) {
  let result = await UserRelation.destroy({
    where: {
      userId,
      followerId
    }
  })
  return result > 0
}


/**
 * 获取关注该用户的用户列表，即该用户的粉丝
 * @method getUsersByFollower
 * @param {number} followerId 被关注人的 id
 */

async function getUsersByFollower(followerId) {
  let result = await User.findAndCountAll({
    attributes: ['id','picture','userName','nickName'],
    include: [
      {
        model: UserRelation,
        where: {
          followerId,
          userId: {
            [Sequelize.Op.ne]: followerId
          } 
        }
      }
    ],
    order: [
      ['id', 'desc']
    ]
  })
  // 设施话userRelation
  let userList = result.rows.map(row => row.dataValues)
  return {
    count: result.count,
    userList
  }
}

/**
 * 获取关注人列表
 * @method getFollowersByUser
 * @param {number} userId 被关注人的 id
 */

async function getFollowersByUser(userId) {
  let result = await UserRelation.findAndCountAll({
    order: [
      ['id', 'desc']
    ],
    where: {
      userId,
      followerId: {
        [Sequelize.Op.ne]: userId //不包括
      } 
    },
    include: {
      model: User,
      attributes: ['id', 'nickName', 'picture']
    }
  })
  let userList = result.rows.map(row => row.dataValues)

  userList = userList.map(item => {
    let user = item.user
    user = user.dataValues
    user = formatUser(user)
    return user
  })
  
  return {
    count: result.count,
    userList
  }
}


module.exports = {
  addFollower,
  deleteFollower,
  getUsersByFollower,
  getFollowersByUser
}